import random, logging
import re
from django.views import View
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework_jwt.authentication import jwt_decode_handler

from yc1997512.serializers.articlelist import ArticleSerializer
from yc1997512.utils import Page

logger = logging.getLogger('django')
from django.http import JsonResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from xyz.models import Channel, Article, User
from rest_framework.response import Response


class SMSCodeView(View):

    def get(self, request, mobile):
        '''接收参数, 检验, 发送短信验证码'''

        # 额外增加的功能: 避免频繁发送短信验证码
        #  从redis中2号库 获取60s保存的信息
        redis_conn = get_redis_connection('verify_code')

        flag = redis_conn.get('flag_%s' % mobile)

        #  判断该值是否存在, 如果不存在, 进行下面的步骤, 如果存在, 返回
        if flag:
            return JsonResponse({'code': 400,
                                 'errmsg': "请不要频繁发送短信验证码"})

        # mobile是否为手机号格式
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': 'mobile不满足格式要求'})

        # 随机生成6为的短信验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 打印短信验证码
        logger.info(sms_code)

        # 创建redis管道:
        pl = redis_conn.pipeline()

        # 把短信验证码保存到redis 验证码5分钟有效 发送间隔上限1分钟
        pl.setex('sms_%s' % mobile, 300, sms_code)

        pl.setex('flag_%s' % mobile, 60, 1)

        # 执行管道:
        pl.execute()

        # 调用容联云, 发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # 添加一个提示celery抛出任务的提醒:
        # send_sms_verify_code.delay(mobile, sms_code)

        # 返回json 测试返回短信验证码
        return JsonResponse({'sms_code': sms_code,
                             'message': "ok",
                             'success': True})


class ArticleList(ListAPIView):
    '''文章列表'''

    pagination_class = Page
    serializer_class = ArticleSerializer
    def get_queryset(self):
        id =self.request.parser_context.get('kwargs').get('id')
        if id == '-1':
            return Article.objects.all().order_by('-createtime')
            # serializer = ArticleSerializer(article, many=True)

        else:
            return Article.objects.filter(channel=id).order_by('-createtime')
            # serializer = ArticleSerializer(article, many=True)
    # def get(self, request,*args, **kwargs):
    #     id = kwargs.get('id')
    #     if id == '-1':
    #         article = Article.objects.all().order_by('-createtime')
    #         serializer = ArticleSerializer(article, many=True)
    #
    #     else:
    #         article = Article.objects.filter(channel=id).order_by('-createtime')
    #         serializer = ArticleSerializer(article, many=True)
    #     return Response(serializer.data)


# class ArticleList(View):
#     '''文章列表'''
#
#     def get(self, request, id):
#         # 获取参数 page页面未实现
#         id = id
#         try:
#             page = request.GET.get("page")
#         except:
#             pass
#
#         # 链接文章接数据库
#         try:
#             articleset = Article.objects.filter(channel_id=id)
#
#         except Exception as e:
#             return JsonResponse({'message': "文章列表数据库查询失败",
#                                  'success': False})
#
#         # [ {
#         #   id:123, user:{id:22, name:123ss, avatar:cc, articles:{id:11,title:11}}
#         # },]
#
#         # 遍历添加 整合数据
#         results = []
#
#         # 先取出文章id name等
#         for article in articleset:
#
#             # 循环添加用户的信息
#             user = {}
#             # 链接用户数据库 取用户信息
#             try:
#                 user_an = User.objects.filter(id=article.user_id)
#             except Exception as e:
#                 return JsonResponse({'message': "用户数据库查询失败",
#                                      'success': False})
#
#             # 取出粉丝数量,收藏用户的数量,当前是否收藏
#             fans = User.objects.filte
#             articles = {}
#             articles['id'] = article.id
#             articles['title'] = article.title
#
#             user['id'] = user_an.id
#             user['username'] = user_an.username
#             user['avatar'] = user_an.avatar
#             user['articles'] = articles
#
#             # 粉丝与收藏 无
#             results.append({
#                 'id': article.id,
#                 'title': article.title,
#                 'comment': article.content,
#                 'createtime': article.createtime,
#                 'user': user,
#                 'image': article.image
#             })
#
#         return JsonResponse({'message': "用户数据库查询失败",
#                              'success': False,
#                              'results': results})


# 收藏文章
class ArticleCollectView(APIView):

    def put(self, request, id):
        try:
            token = self.request.auth
            toke_user = jwt_decode_handler(token)
            user_id = toke_user["user_id"]
        except Exception as e:
            return Response('收藏失败,请先登录', status=404)

        cil = Article.objects.get(id=id)

        for u in cil.collected_users.all():

            if user_id == u.id:
                cil.collected_users.remove(user_id)
                return Response({
                    'message': '文章取消收藏成功',
                    'success': True
                })

        cil.collected_users.add(user_id)
        return Response({
            'message': '文章收藏成功',
            'success': True
        })

#
# class ArticleContent(View):
#     '''文章详情'''
#     def get(self,request,id):
#         article_id = id
#
#         # 链接文章数据库
#         try:
#             article = Article.objects.filter(id=article_id)
#         except Exception as e:
#             return JsonResponse({'message': "用户数据库查询失败",
#                                  'success': False})
